package cn.xiaoniu.day05;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

import cn.xiaoniu.day05.bean.Request;
import cn.xiaoniu.day05.bean.Response;
import cn.xiaoniu.day05.bean.UserResult;

/**
 * 发布服务
 * @author root
 * 1:端口的监听
 * 2：获取客户端传过来的数据
 * 3：反射执行
 * 4：获取到执行的结果，进行数据的返回
 *
 */
public class Server {
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(9999);
			System.out.println("服务端启动了----");
			while(true){
				//获取连接
				Socket accept = serverSocket.accept();
				System.out.println("有连接了");
				ObjectInputStream ois = new ObjectInputStream(accept.getInputStream());
				Request req = (Request)ois.readObject();
				
				//返回结果
				Response resp = new Response();
				
				try {
					//通过request进行反射运行
					//通过反射，获取class
					Class<?> forName = Class.forName(req.getClassName());
					//通过class获取对象
					Object newInstance = forName.newInstance();
					//通过class获取method对象
					Method method = forName.getMethod(req.getMothedName(), req.getClassType());
					//执行方法，获取返回值
					UserResult userResult = (UserResult)method.invoke(newInstance, req.getValue());
					resp.setUserResult(userResult);
					resp.setStatus("200");
				} catch (Exception e) {
					e.printStackTrace();
					resp.setStatus("500");
				}
				
				//获取输出流，返回数据
				ObjectOutputStream oos = new ObjectOutputStream(accept.getOutputStream());
				oos.writeObject(resp);
				oos.flush();
				
				//释放资源
				accept.shutdownInput();
				accept.shutdownOutput();
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
